namespace OFX.Aggregator.Implementation.Retrieval
{
	#region #using Directives

	using System;
	using System.IO;
	using System.Windows.Forms;

	using Infrastructure;

	#endregion

	public class XmlFileClipboardStatementRetrieval : IStatementRetrieval
	{
		private readonly IStatementInterpreter interpreter;

		public XmlFileClipboardStatementRetrieval(IStatementInterpreter interpreter)
		{
			this.interpreter = interpreter;
		}

		#region IStatementRetrieval Members

		public bool CanRetrieveStatement
		{
			get
			{
				if (Clipboard.ContainsFileDropList())
				{
					var fileDropList = Clipboard.GetFileDropList();

					if (fileDropList.Count == 1 && Path.GetExtension(fileDropList[0]) == ".xml")
					{
						return true;
					}
				}

				return false;
			}
		}

		public Statement GetStatement(DateTime? dateStart, DateTime? dateEnd)
		{
			Statement statement = null;

			if (CanRetrieveStatement)
			{
				var fileDropList = Clipboard.GetFileDropList();

				string fileName = fileDropList[0];

				using (TextReader reader = new StreamReader(fileName))
				{
					string xml = reader.ReadToEnd();

					statement = this.interpreter.InterpretStatement(xml);
				}

				statement.Date = File.GetLastWriteTime(fileName);

				StatementFilter.Filter(statement, dateStart, dateEnd);
			}

			return statement;
		}

		#endregion
	}
}